<template>

  <!---搜索表单-->
  <div class="search-div">
    <el-form label-width="70px" size="small">
      <el-row>
        <el-col :span="12">
          <el-form-item label="关键字">
            <el-input
                v-model="queryDto.keyword"
                style="width: 100%"
                placeholder="用户名、姓名、手机号码"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="创建时间">
            <el-date-picker
                v-model="createTimes"
                type="daterange"
                range-separator="To"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="display:flex">
        <el-button type="primary" size="small" @click="searchUser">
          搜索
        </el-button>
        <el-button size="small" @click="reset">重置</el-button>
      </el-row>
    </el-form>
  </div>

  <!--添加按钮-->
  <div class="tools-div">
    <el-button type="success" size="small" @click="addUser">添 加</el-button>
  </div>
  <!-- 添加或修改对话框 -->
  <el-dialog v-model="dialogVisible" title="添加或修改" width="40%">
    <el-form label-width="120px">
      <el-form-item label="用户名">
        <el-input v-model="sysUser.userName"/>
      </el-form-item>
      <el-form-item v-if="sysUser.id == null" label="密码">
        <el-input type="password" show-password v-model="sysUser.password"/>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="sysUser.name"/>
      </el-form-item>
      <el-form-item label="手机">
        <el-input v-model="sysUser.phone"/>
      </el-form-item>
      <el-form-item label="头像">
        <!--         element plus     默认上传的name就是file, 和你controller启的名字对应上 -->
        <el-upload
            class="avatar-uploader"
            action="http://localhost:8501/admin/system/upload"
            :show-file-list="false"
            :headers="headers"
            :on-success="loadSuccess"
        >
          <img v-if="sysUser.avatar" :src="sysUser.avatar" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="sysUser.description"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!---数据表格-->
  <el-table :data="list" style="width: 100%">
    <el-table-column prop="userName" label="用户名"/>
    <el-table-column prop="name" label="姓名"/>
    <el-table-column prop="phone" label="手机"/>
    <el-table-column prop="avatar" label="头像" #default="scope">
      <img :src="scope.row.avatar" width="50"/>
    </el-table-column>
    <el-table-column prop="description" label="描述"/>
    <el-table-column prop="status" label="状态" #default="scope">
      {{ scope.row.status == 1 ? '正常' : '停用' }}
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间"/>
    <el-table-column label="操作" align="center" width="280" #default="scope">
      <el-button type="primary" size="small" @click="changeSysUser(scope.row)">
        修改
      </el-button>
      <el-button type="danger" size="small" @click="deleteSysUserById(scope.row)">
        删除
      </el-button>
      <el-button type="warning" size="small" @click="showAssignRole(scope.row)">
        分配角色
      </el-button>
    </el-table-column>
  </el-table>


  <!--分配角色对话框 -->
  <el-dialog v-model="dialogRoleVisible" title="分配角色" width="40%">
    <el-form label-width="80px">
      <el-form-item label="用户名">
        <el-input disabled :value="sysUser.userName"></el-input>
      </el-form-item>

      <el-form-item label="角色列表">
        <el-checkbox-group v-model="userRoleIds">
          <el-checkbox v-for="role in allRoles" :key="role.id" :label="role.id">
            {{ role.roleName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="doAssign">提交</el-button>
        <el-button @click="dialogRoleVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <el-pagination
      :page-sizes="[2,5,10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next"
      :total="total"
      v-model:current-page="pageParm.page"
      v-model:page-size="pageParm.limit"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />

</template>

<script setup>
import {ref, onMounted} from 'vue';
import {getSysUserByPage, savaUser, editUser, deleteUserId, addDoAssign} from '@/api/sysUser'
import {selectAll} from '@/api/sysRole'
import {ElMessage} from 'element-plus';
import {ElMessageBox} from 'element-plus'
import {useApp} from '@/pinia/modules/app'
// 定义一个响应式数组, 接收复选框传来的id
const userRoleIds = ref([33, 52])

// 提交分配角色
const doAssign = async () => {
  //拿用户id
  // const uid=sysUser.value.id
  //拿到选择角色的id
  // console.log(uid)
  // console.log(userRoleIds.value)
  let doAssginDto = {
    userId: sysUser.value.id,
    roleIdList: userRoleIds.value
  }
  const {code} = await addDoAssign(doAssginDto)
  if (code === 200) {
    ElMessage.success("分配成功")

    //关闭对话框
    dialogRoleVisible.value = false

  }

}
//模拟数据
const allRoles = ref([
  // {"id":1 , "roleName":"管理员"},
  // {"id":2 , "roleName":"业务人员"},
  // {"id":3 , "roleName":"商品录入员"},
])
// 显示分配角色
const dialogRoleVisible = ref(false)
const showAssignRole = async (row) => {

  // 查询全部角色 和当前用户所拥有的角色
  const {data} = await selectAll(row.id)
  allRoles.value = data.sysRoleList
  userRoleIds.value = data.sysUserRoles


  // 显示对话框
  dialogRoleVisible.value = true

  //显示当前用户的信息
  sysUser.value = row

}


//上传成功的回调函数
const loadSuccess = (response) => {
  //这里response 就是我们后端封装的 result对象
  //给响应式对象复制
  //loadSuccess(response) 是上传成功的回调函数
  // response.data 包含上传成功后的文件 URL（即头像地址）。
  // 这样 sysUser.value.avatar 就能保存 新头像的 URL，从而在前端显示最新上传的头像。
  sysUser.value.avatar = response.data
}
//用户头像上传
const headers = ref({
  token: useApp().authorization.token
})

// 删除用户
const deleteSysUserById = (row) => {
  //提示用户是否删除
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const {code} = await deleteUserId(row.id)
    if (code === 200) {
      ElMessage.success('删除成功')
      fetchData()
    }
  }).catch(() => {
    ElMessage.info('取消删除')
  })


}
// 修改用户
const changeSysUser = (row) => {
  // console.log(row)
  //显示对话框
  dialogVisible.value = true
  //回显数据
  sysUser.value = row
}
//定义用户数据模型
const defaultSysUserForm = {
  id: '',
  userName: "",
  password: "",
  name: "",
  phone: "",
  avatar: "",
  description: ""
}
const sysUser = ref(defaultSysUserForm)
// 提交新增或者保存
const submit = async () => {
  // 新增
  if (!sysUser.value.id) {
    const {code, message} = await savaUser(sysUser.value)
    if (code === 200) {
      ElMessage.success("添加成功")
    } else {
      ElMessage.error(message)
    }
    //   关闭对话框
    dialogVisible.value = false
    //刷新页面
    fetchData()
    //   清空响应式数据, 防止下一次还无用的数据
    sysUser.value = {}
  } else {
    //有id说明是修改
    const {code, message} = await editUser(sysUser.value)
    if (code === 200) {
      ElMessage.success("修改成功")
      //隐藏对话框
      dialogVisible.value = false
      // 清空模型
      sysUser.value = {}
      //刷新界面
      fetchData()
    } else {
      ElMessage.error(message)
    }
  }
}
//对话框是否展示
const dialogVisible = ref(false)
const addUser = () => {
  dialogVisible.value = true
}
// 页数发生改变
const handleCurrentChange = () => {
  fetchData()
}
const handleSizeChange = () => {
  fetchData()
}

onMounted(() => {
  fetchData()
})
// 分页对象
const defautSysUserForm = {
  page: 1,
  limit: 10
}
const pageParm = ref(defautSysUserForm)


// 条件对象
const queryDto = ref({
  keyword: '',
  createTimeBegin: '',
  createTimeEnd: ''
})
// 选择时间的条件
const createTimes = ref([])


const fetchData = async () => {
  console.log(createTimes.value)
  // 判断时间时候合法
  if (createTimes.value.length == 2) {
    queryDto.value.createTimeBegin = createTimes.value[0];
    queryDto.value.createTimeEnd = createTimes.value[1]
  }

  const {code, data} = await getSysUserByPage(pageParm.value.page, pageParm.value.limit, queryDto.value)
  total.value = data.total
  list.value = data.list
}
//  模糊搜索用户
const searchUser = () => {
  fetchData()

}
// 重置
const reset = () => {
  queryDto.value = ""
  createTimes.value = []
  fetchData()
}

// 表格数据模型
const list = ref([
  {"id": 1, "userName": "admin", "name": "admin", "phone": "13121034567", "status": 1, "createTime": "2023-05-11"},
  {"id": 2, "userName": "admin", "name": "admin", "phone": "13121034567", "status": 1, "createTime": "2023-05-11"}
]);

// 初始化分页条数据模型
const total = ref(0)

</script>

<style scoped>
.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>